package com.xungou.shoppingCart.controller;

import com.xungou.shoppingCart.pojo.ShoppingCart;
import com.xungou.shoppingCart.service.IShoppingCartService;
import com.xungou.utils.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Resource
    private IShoppingCartService shoppingCartService;

    @RequestMapping("/add")
    @ResponseBody
    public Map<String, Object> add(ShoppingCart shoppingCart, @RequestParam Map<String, String> params) {
        params.put("userId",UserUtil.getCurrentUser().getId()+"");
        ShoppingCart old = shoppingCartService.getShoppingCartByParams(params);
        int flag;
        if(old!=null){
            old.setNum(shoppingCart.getNum()+old.getNum());
            flag = shoppingCartService.updateByPrimaryKeySelective(old);
        }else{
            shoppingCart.setUserId(UserUtil.getCurrentUser().getId());
            flag = shoppingCartService.insert(shoppingCart);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("flag",flag);
        return result;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(ShoppingCart shoppingCart) {
        int flag = shoppingCartService.deleteByPrimaryKey(shoppingCart.getId());
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("flag",flag);
        return result;
    }

    @RequestMapping("/deleteByIds")
    @ResponseBody
    public Map<String, Object> deleteByIds(@RequestParam Map<String, String> params) {
        int flag = shoppingCartService.deleteByIds(params);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("flag",flag);
        return result;
    }

    @RequestMapping("/list")
    @ResponseBody
    public List<Map<String,Object>> list(@RequestParam Map<String, Object> params){
        List<Map<String,Object>> result = shoppingCartService.list(params);
        return result;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Map<String, Object> update(ShoppingCart shoppingCart) {
        int flag;
        flag = shoppingCartService.updateByPrimaryKeySelective(shoppingCart);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("flag",flag);
        return result;
    }

}